import { ref, reactive } from 'vue'
import type { LocateTB, LocateStore, LocateStatus } from '@/types/locate'
import { WEBSOCKET_CONFIG } from '@/config/constants'

// 本地存储键名
const STORAGE_KEY = 'locate_data'
const HISTORY_STORAGE_KEY = 'locate_history'

// 响应式数据存储
export const locateStore = reactive<LocateStore>({
  current: null,
  history: [],
  status: {
    isConnected: false,
    lastUpdate: undefined,
    error: undefined
  }
})

// WebSocket连接状态
export const wsConnected = ref(false)
export const wsError = ref<string | null>(null)

// WebSocket实例
let websocket: WebSocket | null = null

/**
 * 从localStorage加载历史数据
 */
const loadHistoryData = (): LocateTB[] => {
  try {
    const stored = localStorage.getItem(HISTORY_STORAGE_KEY)
    if (stored) {
      return JSON.parse(stored)
    }
  } catch (error) {
    console.error('加载位置历史数据失败:', error)
  }
  return []
}

/**
 * 从localStorage加载当前数据
 */
const loadCurrentData = (): LocateTB | null => {
  try {
    const stored = localStorage.getItem(STORAGE_KEY)
    if (stored) {
      return JSON.parse(stored)
    }
  } catch (error) {
    console.error('加载当前位置数据失败:', error)
  }
  return null
}

/**
 * 保存当前数据到localStorage
 */
const saveCurrentData = (data: LocateTB | null) => {
  try {
    if (data) {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(data))
    } else {
      localStorage.removeItem(STORAGE_KEY)
    }
  } catch (error) {
    console.error('保存当前位置数据失败:', error)
  }
}

/**
 * 保存历史数据到localStorage
 */
const saveHistoryData = (data: LocateTB[]) => {
  try {
    localStorage.setItem(HISTORY_STORAGE_KEY, JSON.stringify(data))
  } catch (error) {
    console.error('保存位置历史数据失败:', error)
  }
}

/**
 * 更新位置数据
 */
export const updateLocateData = (newData: LocateTB) => {
  // 更新时间戳
  const timestamp = Date.now()
  const dataWithTimestamp = {
    ...newData,
    time_stamp: timestamp
  }

  // 更新当前数据
  locateStore.current = dataWithTimestamp
  locateStore.status.lastUpdate = timestamp
  locateStore.status.error = undefined

  // 添加到历史记录
  locateStore.history.unshift(dataWithTimestamp)

  // 限制历史记录长度，避免数据过多
  if (locateStore.history.length > 1000) {
    locateStore.history = locateStore.history.slice(0, 1000)
  }

  // 持久化存储
  saveCurrentData(dataWithTimestamp)
  saveHistoryData(locateStore.history)

  console.log('位置数据已更新:', dataWithTimestamp)
}

/**
 * 清空位置数据
 */
export const clearLocateData = () => {
  locateStore.current = null
  locateStore.history = []
  locateStore.status.lastUpdate = undefined
  locateStore.status.error = undefined

  saveCurrentData(null)
  saveHistoryData([])
}

/**
 * 获取当前位置数据
 */
export const getCurrentLocateData = (): LocateTB | null => {
  return locateStore.current
}

/**
 * 获取位置历史数据
 */
export const getLocateHistory = (): LocateTB[] => {
  return locateStore.history
}

/**
 * 根据条件查找历史数据
 */
export const findLocateDataBy = (predicate: (data: LocateTB) => boolean): LocateTB[] => {
  return locateStore.history.filter(predicate)
}

/**
 * WebSocket连接配置
 */
export const connectLocateWebSocket = (url?: string) => {
  // 使用配置中的默认URL或传入的自定义URL
  const defaultUrl = `${WEBSOCKET_CONFIG.BASE_URL}${WEBSOCKET_CONFIG.ENDPOINTS.POSITION}`
  const wsUrl = url || defaultUrl
  // 如果已有连接，先关闭
  if (websocket) {
    websocket.close()
  }

  try {
    websocket = new WebSocket(wsUrl)

    websocket.onopen = () => {
      console.log('位置WebSocket连接已建立')
      wsConnected.value = true
      wsError.value = null
      locateStore.status.isConnected = true
      locateStore.status.error = undefined
    }

    websocket.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data) as LocateTB
        console.log('收到位置数据:', data)
        updateLocateData(data)
      } catch (error) {
        console.error('解析位置WebSocket数据失败:', error)
        wsError.value = '数据解析错误'
        locateStore.status.error = '数据解析错误'
      }
    }

    websocket.onerror = (error) => {
      console.error('位置WebSocket错误:', error)
      wsConnected.value = false
      wsError.value = 'WebSocket连接错误'
      locateStore.status.isConnected = false
      locateStore.status.error = 'WebSocket连接错误'
    }

    websocket.onclose = (event) => {
      console.log('位置WebSocket连接已关闭:', event.code, event.reason)
      wsConnected.value = false
      locateStore.status.isConnected = false

      // 如果不是主动关闭，尝试重连
      if (event.code !== 1000) {
        wsError.value = 'WebSocket连接断开'
        locateStore.status.error = 'WebSocket连接断开'
        setTimeout(() => {
          console.log('尝试重连位置WebSocket...')
          connectLocateWebSocket(wsUrl)
        }, 5000) // 5秒后重连
      }
    }

  } catch (error) {
    console.error('创建位置WebSocket连接失败:', error)
    wsError.value = 'WebSocket创建失败'
    locateStore.status.error = 'WebSocket创建失败'
  }
}

/**
 * 断开WebSocket连接
 */
export const disconnectLocateWebSocket = () => {
  if (websocket) {
    websocket.close(1000, '主动断开连接')
    websocket = null
  }
  wsConnected.value = false
  wsError.value = null
  locateStore.status.isConnected = false
  locateStore.status.error = undefined
}

/**
 * 初始化位置数据服务
 */
export const initLocateService = () => {
  // 加载持久化数据
  locateStore.current = loadCurrentData()
  locateStore.history = loadHistoryData()

  console.log('已加载位置数据 - 当前:', locateStore.current)
  console.log('已加载位置历史:', locateStore.history.length, '条')
}

/**
 * 获取格式化的位置信息用于StatusDisplay组件
 */
export const getPositionForStatusDisplay = () => {
  const current = locateStore.current
  if (!current) return {}

  return {
    LineName: current.LineName,
    POL: current.POL,
    KMV: current.KMV?.toString(),
    STN: current.STN,
    TUN: current.TUN,
    Updown: current.Updown,
    SPD: current.SPD,
    lastUpdate: locateStore.status.lastUpdate
  }
}